import { getHttp,http } from '@/api/http'
import { getToken } from '@/utils/auth'
import { chat } from './protobuf-loader'
import { fileMd5, strMd5 } from '@/utils/md5'

/**
 * 获取或创建私聊会话
 * @param {string} targetEmail 目标用户邮箱
 * @returns {Promise<{success: boolean, message: string, session_id?: string, is_new?: boolean, session_info?: Object}>}
 */
export const getOrCreatePrivateSession = async (targetEmail) => {
    const request = new chat.GetOrCreatePrivateSessionRequest();
    request.setToken(getToken());
    request.setTargetEmail(targetEmail);
    
    const responseData = await getHttp().post('/chat/get_or_create_private_session', request.serializeBinary());
    const response = chat.GetOrCreatePrivateSessionResponse.deserializeBinary(responseData.data);
    
    if (responseData.status !== 200) {
        throw "请求失败";
    }
    
    if (!response.getSuccess()) {
        throw response.getMessage();
    }
    console.log(response.toObject());
    const result = {
        success: response.getSuccess(),
        message: response.getMessage(),
        session_id: response.getSessionId(),
        is_new: response.getIsNew(),
        session_info: null
    };
    
    // 如果有会话详细信息，则添加到结果中
    if (response.getSessionInfo()) {
        const sessionInfo = response.getSessionInfo();
        result.session_info = {
            id: sessionInfo.getId(),
            name: sessionInfo.getName(),
            is_group: sessionInfo.getIsGroup(),
            avatar: sessionInfo.getAvatar(),
            last_read_message_id: sessionInfo.getLastReadMessageId(),
            updated_at: sessionInfo.getUpdatedAt(),
            is_pinned: sessionInfo.getIsPinned()
        };
    }
    
    return result;
};

// 获取回话列表
export const getSessions = async (page, page_size) => {
    const request = new  chat.GetSessionsRequest();
    request.setToken(getToken());
    request.setPage(page);
    request.setPageSize(page_size);
    const responseData = await getHttp().post('/chat/get_sessions', request.serializeBinary());
    const response = chat.GetSessionsResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200) {
        throw "请求失败";
    }
    if (response.getSuccess() === false) {
        throw response.getMessage();
    }
    return {
        sessions: response.getSessionsList().map(session => ({
            id: session.getId(),
            name: session.getName(),
            is_group: session.getIsGroup(),
            is_pinned: session.getIsPinned(),
            avatar: session.getAvatar(),
            last_read_message_id: session.getLastReadMessageId(),
            updated_at: session.getUpdatedAt(),
        })),
        total: response.getTotal()
    };
}

// 获取回话的消息内容
export const getSessionMessages = async (session_id, page, page_size) => {
    const request = new chat.GetSessionMessagesRequest();
    request.setToken(getToken());
    request.setSessionId(session_id);
    request.setPage(page);
    request.setPageSize(page_size);
    const responseData = await getHttp().post('/chat/get_session_messages', request.serializeBinary());
    const response = chat.GetSessionMessagesResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200) {
        throw "请求失败";
    }
    if (response.getSuccess() === false) {
        throw response.getMessage();
    }
    return {
        messages: response.getMessagesList().map(message => ({
            id: message.getMessageId(),
            session_id: message.getSessionId(),
            from_id: message.getFromId(),
            send_at: message.getSendAt(),
            type: message.getType(),
            text: message.getText(),
            image: {
                id: message.getImage()?.getId(),
                path: message.getImage()?.getPath() || '',
            }
        })),
        total: response.getTotal()
    }
}

// 加载更多消息（基于最早消息ID加载更多历史消息）
export const loadMoreMessages = async (session_id, last_message_id, page_size = 10) => {
    const request = new chat.LoadMoreMessagesRequest();
    request.setToken(getToken());
    request.setSessionId(session_id);
    request.setLastMessageId(last_message_id);
    request.setPageSize(page_size);
    const responseData = await getHttp().post('/chat/load_more_messages', request.serializeBinary());
    const response = chat.LoadMoreMessagesResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200) {
        throw "请求失败";
    }
    if (response.getSuccess() === false) {
        throw response.getMessage();
    }
    return {
        messages: response.getMessagesList().map(message => ({
            id: message.getMessageId(),
            session_id: message.getSessionId(),
            from_id: message.getFromId(),
            send_at: message.getSendAt(),
            type: message.getType(),
            text: message.getText(),
            image: {
                id: message.getImage()?.getId(),
                path: message.getImage()?.getPath() || '',
            }
        })),
        has_more: response.getHasMore(),
        total: response.getTotal()
    }
}

// 获取好友列表
export const getFriends = async (ids) => {
    const request = new chat.GetFriendsRequest();
    request.setToken(getToken());
    request.addUserIdsList(ids);
    const responseData = await getHttp().post('/chat/get_friends', request.serializeBinary());
    const response = chat.UsersResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200) {
        throw "请求失败";
    }
    if (response.getSuccess() === false) {
        throw response.getMessage();
    }
    return {
        users: response.getUserList().map(user => ({
            name: user.getName(),
            email: user.getEmail(),
            avatar: user.getAvatar(),
        })),
        total: response.getTotal()
    }
}
// 获取关注我的用户列表
export const getFollowers = async (email, page, page_size) => {
    const request = new chat.GetFollowersRequest();
    request.setToken(getToken());
    request.setEmail(email);
    request.setPage(page);
    request.setPageSize(page_size);
    const responseData = await getHttp().post('/chat/get_followers', request.serializeBinary());
    const response = chat.GetFollowersResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200) {
        throw "请求失败";
    }
    if (response.getSuccess() === false) {
        throw response.getMessage();
    }
    return {
        users: response.getUserList().map(user => ({
            id: user.getId(),
            name: user.getName(),
            email: user.getEmail(),
            avatar: user.getAvatar(),
        })),
        total: response.getTotal()
    }
}

// 获取我关注的用户列表
export const getFollowing = async (email, page, page_size) => {
    const request = new chat.GetFollowingRequest();
    request.setToken(getToken());
    request.setEmail(email);
    request.setPage(page);
    request.setPageSize(page_size);
    const responseData = await getHttp().post('/chat/get_following', request.serializeBinary());
    const response = chat.GetFollowingResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200) {
        throw "请求失败";
    }
    if (response.getSuccess() === false) {
        throw response.getMessage();
    }
    return {
        users: response.getUserList().map(user => ({
            id: user.getId(),
            name: user.getName(),
            email: user.getEmail(),
            avatar: user.getAvatar(),
        })),
        total: response.getTotal()
    }
}

// 获取互相关注的用户列表
export const getMutualFollowers = async (page, page_size) => {
    const request = new chat.GetMutualFollowersRequest();
    request.setToken(getToken());
    request.setPage(page);
    request.setPageSize(page_size);
    const responseData = await getHttp().post('/chat/get_mutual_followers', request.serializeBinary());
    const response = chat.GetMutualFollowersResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200) {
        throw "请求失败";
    }
    if (response.getSuccess() === false) {
        throw response.getMessage();
    }
    return {
        users: response.getUserList().map(user => ({
            id: user.getId(),
            name: user.getName(),
            email: user.getEmail(),
            avatar: user.getAvatar(),
        })),
        total: response.getTotal()
    }
}



// 获取收藏的表情包
export const getFavoriteEmojis = async () => {
    const request = new chat.GetFavoriteEmojisRequest();
    request.setToken(getToken());
    const responseData = await getHttp().post('/chat/get_favorite_emojis', request.serializeBinary());
    const response = chat.GetFavoriteEmojisResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200) {
        throw new Error("请求失败");
    }
    if (response.getSuccess() === false) {
        throw new Error(response.getMessage());
    }
    return {
        images: response.getImagesList().map(image => ({
            id: image.getId(),
            name: image.getName(),
            url: image.getUrl(),
        })),
        total: response.getTotal()
    }
}
// 添加收藏的表情
export const addFavorite = async (image) => {
    const request = new chat.AddFavoriteRequest();
    request.setToken(getToken());
    request.setImagePath(image);
    const responseData = await getHttp().post('/chat/add_favorite', request.serializeBinary());
    const response = chat.AddFavoriteResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200) {
        throw new Error("请求失败");
    }
    if (response.getSuccess() === false) {
        throw new Error(response.getMessage());
    }
    
    return {
        success: response.getSuccess(),
        msg: response.getMessage(),
    };
}







